using Dapper;
using Finance.Api.Read.Applications.Commands.库存调拨;
using Finance.Domain.调拨;
using Finance.ErrorCode;
using Finance.Infrastructure;
using MediatR;

namespace Finance.Api.Read.Applications.CommandHands.库存调拨
{
    public class DeploymentDetailQueryCommandHandlers : IRequestHandler<DeploymentDetailQueryCommand, ApiResult<List<DeploymentDetail>>>
    {
        private readonly IDapperDb _db;
        private readonly ILogger<DeploymentDetailQueryCommandHandlers> _logger;

        public DeploymentDetailQueryCommandHandlers(IDapperDb db, ILogger<DeploymentDetailQueryCommandHandlers> logger)
        {
            _db = db;
            _logger = logger;
        }

        public async Task<ApiResult<List<DeploymentDetail>>> Handle(DeploymentDetailQueryCommand request, CancellationToken cancellationToken)
        {
            var result = new ApiResult<List<DeploymentDetail>>();
            var parameters = new DynamicParameters();

            try
            {
                parameters.Add("@DeploymentId", request.DeploymentId);

                var sql = @"SELECT 
                            Id,
                            Deploymentid,
                            ProductNo,
                            ProductName,
                            ProductNum,
                            DeploymentNum,
                            DeploymentMessage,
                            CreateTime,
                            CreateName,
                            UpdateTime,
                            UpdateName,
                            DeleteTime,
                            DeleteName,
                            IsDelete
                        FROM DeploymentDetail 
                        WHERE Deploymentid = @DeploymentId AND IsDelete = 0
                        ORDER BY Id ASC";

                var list = await _db.Query<DeploymentDetail>(sql, parameters);
                
                result.data = list.ToList();
                result.message = "获取调拨明细成功";
                result.Code = Enumcode.ok;
            }
            catch (Exception ex)
            {
                _logger.LogError("获取调拨明细失败: {Message}", ex.Message);
                result.message = "获取调拨明细失败";
                result.Code = Enumcode.fail;
                throw;
            }

            return await Task.FromResult(result);
        }
    }
} 